package com.aidex.biz.utils;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class AliQwenUtils {
    public static final String API_KEY = "sk-277643488a6c4ba9893e427ee50655f8";
    public static final String APP_ID = "f87bdbf37dfa4b68a26566fc6f9e22b9";

    public static void main(String[] args) {
        try {
            //  appCall();
            simpleMultiModalConversationCall(null);
        } catch (ApiException | NoApiKeyException e) {
            System.err.println("message：" + e.getMessage());
            System.out.println("请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code");
        } catch (UploadFileException e) {
            throw new RuntimeException(e);
        }
        System.exit(0);
    }

    public static void appCall() throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey(API_KEY).appId(APP_ID).prompt("新能源车2年,黑户").incrementalOutput(true).build();

        Application application = new Application();
        Flowable<ApplicationResult> result = application.streamCall(param);
        result.blockingForEach(data -> {
            System.out.printf("%s\n", data.getOutput().getText());
        });

    }

    /**
     * 语音转文字
     *
     * @throws ApiException
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    public static String simpleMultiModalConversationCall(String audioUrl) throws ApiException, NoApiKeyException,
            UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage =
                MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap("audio", audioUrl))).build();

        MultiModalConversationParam param =
                MultiModalConversationParam.builder().apiKey(API_KEY).model("qwen-audio" + "-asr").message(userMessage).build();
        MultiModalConversationResult result = conv.call(param);
        try {
            return (String) result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text");
        } catch (Exception e) {
            return null;
        }
    }

    public static GenerationResult callWithMessage(String audioUrl) throws ApiException, NoApiKeyException,
            InputRequiredException, UploadFileException {
        Generation gen = new Generation();
        String content = simpleMultiModalConversationCall(audioUrl);
        Message userMsg = Message.builder().role(Role.USER.getValue()).content(content).build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(API_KEY).model("qwen-plus").messages(Arrays.asList(userMsg))
                // 不可以设置为"text"
                .resultFormat(GenerationParam.ResultFormat.MESSAGE).build();
        return gen.call(param);
    }

    public static void main1(String[] args) {
        try {
            GenerationResult result = callWithMessage(null);
            System.out.println("思考过程：");
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getReasoningContent());
            System.out.println("回复内容：");
            List<String> content =
                    Arrays.stream(result.getOutput().getChoices().get(0).getMessage().getContent().replace("*", "").split("\n")).collect(Collectors.toList());
            content.forEach(System.out::println);
        } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {
            // 使用日志框架记录异常信息
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }

}
